﻿using Micro.Extensions.Utilities;
using Micro.Srv.LogCenter.Services.Interfaces;
using Microsoft.Extensions.Options;
using Nest;
using System.Linq;
using System.Threading.Tasks;

namespace Micro.Srv.LogCenter.Services
{
    public class SystemConfigService : ISystemConfigService
    {
        private readonly ElasticClient _client;
        private readonly IOptions<ElasticSearchOptions> _options;

        public SystemConfigService(ElasticClientHelper elasticClientHelper, IOptions<ElasticSearchOptions> options)
        {
            _client = elasticClientHelper.ElasticClient;
            _options = options;
        }

        public async Task<ComResult<bool>> AddSystemConfigAsync(SystemConfigViewModel systemConfig)
        {
            var response = await _client.SearchAsync<SystemConfigViewModel>(s => s
             .Index(_options.Value.DefaultSystemConfigIndex)
             .From(0)
             .Size(1)
             .Query(q => q.Term(t => t.Field(f => f.Id).Value(systemConfig.Id))));

            if (response.ApiCall.Success && response.Hits.Count > 0)
                return ComResult.Failed<bool>(-1, "Application Id 已存在");
            else
            {
                var indexResponse = await _client.IndexAsync(systemConfig, s => s
                .Index(_options.Value.DefaultSystemConfigIndex));

                if (indexResponse.ApiCall.Success)
                    return ComResult.Success(true);
                else
                    return ComResult.Failed<bool>(-1, "插入文档错误！");
            }
        }

        public async Task<ComResult<SystemConfigViewModel[]>> GetSystemConfigsAsync(int pageIndex, int pageSize)
        {
            var response = await _client.SearchAsync<SystemConfigViewModel>(s => s
                   .Index(_options.Value.DefaultSystemConfigIndex)
                   //.Type("doc")
                   .From(pageIndex * pageSize)
                   .Size(pageSize));

            if (response.ApiCall.Success)
            {
                var result = response.Hits.Select(s =>
                {
                    s.Source.Id = s.Id;
                    return s.Source;
                }).ToArray();

                return ComResult.Success(result, new AttachPage(pageIndex, pageSize, response.Total));
            }

            response.TryGetServerErrorReason(out string reason);
            return ComResult.Failed<SystemConfigViewModel[]>(400, reason);
        }
    }
}
